import * as odbc from "odbc";
import { BrowserWindow, ipcMain } from "electron";
import mssql from "mssql";

export default (win: BrowserWindow) => {
  ipcMain.on("load-online-mssql-data", async (event, config) => {
    //    const queryString = `select Pat_Name,Pat_Sex,Pat_ID,Pat_TestNo,Pat_Sending_Date,
    // Pat_Testing_Date,Pat_Report_Date,Pat_Test_Time,Pat_Doctor,Pat_Checker from Dr_patient where Pat_id>=13000 and  Pat_Sending_Date=#${config.queryDate}#`
    const queryString = `select Patient.*  from SampleMain  
    left join Patient ON SampleMain.PatientUID=Patient.UID   
    where ApplicationTime>'${config.queryDate}' and ApplicationTime<'${config.queryDate} 23:59:59' 
    and SampleMain.CombItemNames='老年人体检'
    `;

    const createQueryStringItem = (UID) => {
      return `select Patient.*,ItemMain.Item,ItemMain.FullName,ItemMain.Unit,SampleResult.Concentration,SampleResult.Flag,SampleResult.NormalLow,SampleResult.NormalHigh  from SampleMain  
    left join Patient ON   SampleMain.PatientUID=Patient.UID  
    left join SampleResult ON   SampleResult.SampleID=SampleMain.SampleID 
    left join ItemMain ON   ItemMain.ItemID=SampleResult.ItemID 
    where ApplicationTime>'${config.queryDate}' and ApplicationTime<'${config.queryDate} 23:59:59'
    and SampleMain.CombItemNames='老年人体检'  and UID='${UID}'
    `;
    };

    console.log("1111");
    const sqlConfig = {
      user: config.user,
      password: config.password,
      database: config.database,
      server: config.server,
      port: config.port,
      // password: "11111111",
      // database: "yyyy_test",
      // server: "localhost",

      options: {
        encrypt: false,
        // trustServerCertificate: false,
      },
    };

    try {
      await mssql.connect(sqlConfig);

      const request = new mssql.Request();
      const query = (sql) => {
        return new Promise((resolve, reject) => {
          request.query(sql, (err, result) => {
            if (err) {
              reject(err);
            }
            resolve(result.recordset as Array<any>);
          });
        });
      };
      const resultData = (await query(queryString)) as Array<any>;
      // `select Pat_Name,Pat_Sex,Pat_ID,Pat_TestNo,Pat_Sending_Date,Pat_Testing_Date,Pat_Report_Date,Pat_Test_Time,Pat_Doctor,Pat_Checker
      if (resultData && resultData.length) {
        for (let i = 0; i < resultData.length; i++) {
          const itemResult = (await query(
            createQueryStringItem(resultData[i].UID)
          )) as Array<any>;

          var resultItem = [];
          for (let j = 0; j < itemResult.length; j++) {
            const d = itemResult[j];
            resultItem.push({
              TestName: d.Item,
              TestCnName: d.FullName,
              TestResult: d.Concentration.toFixed(2),
              TestRange: d.NormalLow + "-" + d.NormalHigh,
              TestUnit: d.Unit,
            });
          }
          resultData[i].result = resultItem;
        }

        // console.log(resultData);
        win.webContents.send(
          "send-online-mssql-data",
          resultData.map((item) => {
            return {
              Pat_Sending_Date: config.queryDate,
              Pat_Name: item.Name,
              Pat_Sex: item.Sex,
              Pat_ID: item.UID,
              result: item.result,
            };
          })
        );

        // return {
        //   Pat_Name: item.Name,
        //   Pat_Sex: item.Sex,
        //   Pat_ID: item.UID,
        //   result:
        // };
      }
    } catch (err) {
      console.log(err);
    }
    //
    //
    // try {
    //   const connect = await odbc.connect(dbInfo);
    //   const data:Array<any> = await connect.query(queryString)
    //   for (let item of data) {
    //     const queryItemString = `select
    //         DR_Test_App.TestName,
    //         DR_Test_App.TestCnName ,
    //         DR_Test_App.TestResult,
    //          DR_Test_App.TestRange,
    //          DR_Test_App.TestUnit
    //          from Dr_patient
    //          left join DR_Test_App
    //          on
    //          Dr_Patient.Pat_TestNo=DR_Test_App.TestNo
    //          and
    //          Dr_Patient.Pat_Sending_Date=DR_Test_App.TestDate
    //          where
    //          Pat_id=${item.Pat_ID}
    //          order by
    //          DR_Test_App.ID asc`
    //     try {
    //       item.result = await connect.query(queryItemString);
    //       console.log("result",item.result)
    //     }catch (e) {
    //       console.log(2333,e)
    //     }
    //   }
    //   win.webContents.send("send-access-data", data)
    // } catch (e) {
    //   console.log(222,e)
    //   win.webContents.send("send-access-data", [])
    // }
  });
};
